// #ifdef H5
import h5Copy from "@/common/junyi-h5-copy/junyi-h5-copy.js"
// #endif

import Vue from "vue"
import { mapState } from "vuex"
import api from '@/api/index.js'
import { formatTime, plusXing } from "@/utils/index.js"

export default {
	data() {
		return {
			request: false,
		}
	},
	computed: {
		...mapState({
			user: 'user_info',
		}),
		i18n_t() {
			return function(name) {
				return this.$t('t')[name] || name; // uniapp 不支持在取值表达式中直接调方法，因此，$t方法不可用，所以通过计算属性的方式：
			}
		},
		option: function() {
			return this.$store.state.option
		},
		// 网络图片
		getAppImg: function() {
			return function(img) {
				// return `${this.$config.appImgURL}/app-image/${img}`
				return `/static/images/${img}`
			}

		},
		isLogin() {
			if (!this.$store.state.user_info) return false;
			return true;
		},
		getContentArr: function() {
			return function(content) {
				return content.split("/n")
			}
		},

		getFileType: function() {
			return function(fileName) {
				if (!fileName) return ""
				const extension = fileName.split('.').pop().toLowerCase();
				if (['mp4', 'mov', 'm4v', 'avi', 'mpg', 'webm'].includes(extension)) {
					return 'video';
				} else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
					return 'image';
				} else {
					return '';
				}

			}
		}



	},
	methods: {
		...{
			formatTime,
			plusXing,
		},
		getUserInfo(type = null) {
			return new Promise((resolve, reject) => {
				this.api.post("/api/user/user_content").then(res => {
					let data = res;
					this.$store.commit("setUserInfo", res)
					resolve(user)
				}).catch(err => {
					this.loadingHide();
					resolve(false)
				})
			})
		},

		getImageSrc(src, type = 'server') {
			if (!src) return ''
			if (src.charAt(0) === '/' && type === 'oss') return this.$config.imgURL + src //图片在oss
			if (src.charAt(0) === '/' && type === 'server') return this.$config.imgURL + src //图片在服务器
			return src
		},
		goBack() {
			const pages = getCurrentPages()

			if (pages.length > 1) {
				//  #ifdef H5
				history.back()
				// #endif

				// #ifndef H5
				uni.navigateBack({
					animationDuration: 200
				});
				// #endif
			} else {
				uni.reLaunch({
					url: "/pages/home/index"
				})
			}

		},
		call(phone) {
			uni.makePhoneCall({
				phoneNumber: phone
			});

		},
		// 复制
		copy(content) {
			// #ifdef H5
			const result = h5Copy(String(content))
			this.success(this.i18n_t('复制成功') || "copy success")
			// #endif

			// #ifdef APP
			uni.setClipboardData({
				data: String(content),
				success: () => {
					uni.hideToast()
					this.success(this.i18n_t('复制成功') || "copy success")
				}
			});
			// #endif
			// #ifdef MP-WEIXIN
			wx.setClipboardData({
				data: String(content),
				success: (res) => {
					console.log("复制成功");
				},
				fail: (err) => {
					console.log(err);
				}
			})
			// #endif

		},
		// 图片预览
		showImg(img, current = 0) {
			const images = img.map(e => {
				return this.getImageSrc(e)
			})
			// 预览图片
			uni.previewImage({
				current: current,
				urls: images,
			});
		},
		//
		openWin(url) {
			uni.navigateTo({
				url: url
			})
		},
		showModalMsg(content) {
			uni.showModal({
				title: this.i18n_t('提示') || '提示', //提示
				content: content,
				showCancel: false,
				confirmText: this.i18n_t('我知道了') || '我知道了' //我知道了
			})
		},
		// 提示框
		toast(text, duration = 1200) {
			// #ifdef APP-PLUS
			plus.nativeUI.toast(text)
			// #endif

			// #ifndef APP-PLUS
			uni.showToast({
				title: text,
				duration: duration,
				icon: 'none'
			});
			// #endif

		},
		successBox(content, title = "TIPS") {
			uni.showModal({
				title: this.i18n_t('提示') || '提示', //提示
				content: content,
				showCancel: false,
				confirmText: this.i18n_t('我知道了') || '我知道了' //我知道了
			});
		},
		// 成功提示框
		success(text, duration = 1500) {
			if (this.$refs.uToast) {
				this.$refs.uToast.show({
					type: 'success',
					message: text,
					icon: false,
					duration: duration,
					position: 'bottom'
				})
			} else {
				uni.showToast({
					title: text,
					duration: duration,
					icon: 'none'
				});
			}
		},
		// 错误提示框
		fail(text, duration = 1500) {

			if (this.$refs.uToast) {
				this.$refs.uToast.show({
					type: 'error',
					icon: false,
					message: text,
					duration: duration,
					position: 'bottom'
				})
			} else {
				uni.showToast({
					title: text,
					duration: duration,
					icon: 'none'
				});
			}


		},
		// 显示加载框  //不会自动关闭
		loadingShow(text = '') {
			uni.showLoading({
				title: text ? text : 'Loading',
				mask: true
			});
		},
		// 关闭加载框
		loadingHide() {
			uni.hideLoading()
		},

		// 接口报错提示
		apiErr(err) {
			this.loadingHide()
			if (err.msg) {
				this.fail(err.msg)
				return
			}
			if (err.message) {
				this.fail(err.message)
				return
			}
			this.fail("系统错误")
		},
		// 防抖处理
		isRequest() {
			if (this.request) return true;
			this.request = true;
			setTimeout(() => {
				this.request = false;
			}, 2000)
			return false;
		},

		uploadFile(FilePath) {
			return new Promise((resolve, reject) => {

				if (FilePath.charAt(0) === '/') {
					return resolve({
						url: FilePath
					})
					return false
				}

				uni.uploadFile({
					url: `${this.$config.baseURL}/api/common/upload`, //图片上传接口
					filePath: FilePath,
					name: 'file',
					header: {
						token: this.$store.state.token || ''
					},
					success: async (uploadFileRes) => {
						if (uploadFileRes.statusCode !== 200) {
							this.fail(this.i18n_t('上传失败'))
							return reject({
								url: ""
							})
						}
						const data = JSON.parse(uploadFileRes.data);

						if (data.code !== 1) {
							this.fail(this.i18n_t('上传失败'))
							return reject({ url: "" })
						}
						resolve({ url: data.data.url });
					},
					fail: (err) => {
						this.fail(this.i18n_t('上传失败'))
						reject({ url: "" })
					}
				});
			})
		},
		openWeb(url) {
			if (!url) return false
			// #ifdef APP-PLUS
			plus.runtime.openURL(url);
			// #endif
			// #ifdef H5
			window.open(url)
			// #endif
		},
		// 打开view
		openWebView(url, title) {
			// #ifdef H5
			this.openWin(`/pages/web-view/web-view?web=${encodeURIComponent(JSON.stringify(url))}&title=${title}`)
			// #endif

			// #ifdef APP-PLUS
			plus.runtime.openWeb(url);
			// #endif
		},

		formatRichText(html) {
			if (html === null || html === undefined || html === 'null') return ""
			let newContent = html.replace(/<img[^>]*>/gi, function(
				match,
				capture
			) {
				match = match
					.replace(/style="[^"]+"/gi, "")
					.replace(/style='[^']+'/gi, "");
				match = match
					.replace(/width="[^"]+"/gi, "")
					.replace(/width='[^']+'/gi, "");
				match = match
					.replace(/height="[^"]+"/gi, "")
					.replace(/height='[^']+'/gi, "");
				return match;
			});
			newContent = newContent.replace(/style="[^"]+"/gi, function(
				match,
				capture
			) {
				match = match
					.replace(/width:[^;]+;/gi, "max-width:100%;")
					.replace(/width:[^;]+;/gi, "max-width:100%;");
				return match;
			});
			newContent = newContent.replace(/<br[^>]*\/>/gi, "");
			newContent = newContent.replace(
				/\<img/gi,
				'<img style="max-width:100%;height:auto;display:block;"'
			);

			newContent = newContent.replace(/style\=\"\"/gi, '')
			const regex = new RegExp('src="/', 'gi');
			newContent = newContent.replace(regex, 'src="' + this.$config.imgURL + '/');
			return newContent;
		},

		getHtml(html) {
			return html.replace(/<img/gi, '<img style="max-width:100%;height:auto;margin:0 auto;display:block"')
		},



		// 打开网页
		browserOpen(url, title = "") {
			// #ifdef H5
			this.openWin(`/pages/web-view/web-view?web=${encodeURIComponent(JSON.stringify(url))}&title=${title}`)
			return
			// #endif
			// #ifdef APP-PLUS
			plus.runtime.openURL(url, () => {
				this.openWin(`/pages/web-view/web-view?web=${encodeURIComponent(JSON.stringify(url))}&title=${title}`)
			});
			// #endif

		},
		checkLogin() {
			if (!this.isLogin) {
				uni.showModal({
					showCancel: false,
					confirmText: this.fail(this.i18n_t('去登录')) || "去登录",
					title: this.fail(this.i18n_t('提示')) || "提示",
					content: this.fail(this.i18n_t('未登录，请先登录')) || "未登录，请先登录",
					success: (res) => {
						if (res.confirm) {
							this.$store.commit('loginout')
							this.appletLogin()
						}
					}
				})
				return false
			}
			return true
		},
		//设置页面标题
		// setTitle(title) {
		// 	// #ifdef APP
		// 	uni.setNavigationBarTitle({
		// 		title: title
		// 	})
		// 	// #endif
		// 	// #ifdef H5
		// 	window.document.title = title
		// 	// #endif
		// },
		//小程序登录
		async appletLogin() {
			const params = {
				code: await this.getLoginCode()
			}
			this.api.post("/api/login", {
				params: params
			}).then(async (res) => {
				const token = res.token;
				this.$store.commit('login', token)
				await this.getUserInfo()
			}).catch(err => {
				this.apiErr(err)
			})
		},
		getLoginCode() {
			return new Promise((resolve, reject) => {

				uni.login({
					provider: 'weixin',
					success: (res) => {
						resolve(res.code)
					},
					fail: (err) => {
						reject("")
					}
				});
			})
		},
	}
}